package main

import (
	"database/sql"
	"fmt"
	"log"
	"time"
)
import _ "github.com/go-sql-driver/mysql"


var db *sql.DB

func init() {
	db, _ = sql.Open(
		"mysql",
		"root:root@tcp(172.20.0.10:3306)/gogogo?charset=utf8&parseTime=true&loc=Local",
	)
	db.SetMaxOpenConns(100)
}

func main() {
	//batchInsertWithoutTx()
	batchInsertStudent()
}

func batchInsertWithoutTx() {
	var stuNo string
	for i := 0; i < 10; i++ {
		stmt, _ := db.Prepare("INSERT INTO tbl_student (stu_no, name, create_time) VALUES (?, ?, ?)")
		stuNo = fmt.Sprintf("2020002000%d", i)
		if i == 5 {
			stuNo = "20200020001"
		}
		stmt.Exec(stuNo, "李四", time.Now())
	}
}

// 带事务的提交
func batchInsertStudent() {
	tx, _ := db.Begin()
	defer tx.Rollback()
	var stuNo string
	for i := 0; i < 10; i++ {
		stmt, _ := tx.Prepare("INSERT INTO tbl_student (stu_no, name, create_time) VALUES (?, ?, ?)")
		stuNo = fmt.Sprintf("2020002000%d", i)
		if i == 5 {
			stuNo = "20200020001"
		}
		_, err := stmt.Exec(stuNo, "李四", time.Now())
		if err != nil {
			log.Println("insert error.", err.Error())
			return
		}
	}
	tx.Commit()
}